package org.jeecg.modules.tt_question_collect.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.tt_question_collect.entity.TtAuditRecord;
import org.jeecg.modules.tt_question_collect.entity.TtCollectFlowNode;
import org.jeecg.modules.tt_question_collect.entity.TtQuestionCollect;
import org.jeecg.modules.tt_question_collect.mapper.TtCollectFlowNodeMapper;
import org.jeecg.modules.tt_question_collect.service.ITtAuditRecordService;
import org.jeecg.modules.tt_question_collect.service.ITtCollectFlowNodeService;
import org.jeecg.modules.tt_question_collect.service.ITtQuestionCollectService;
import org.jeecg.modules.tt_question_collect.util.AuditNodeType;
import org.jeecg.modules.tt_question_collect.util.MsgTypeEnum;
import org.jeecg.modules.tt_question_collect.util.PushSysMsgUtil;
import org.jeecg.modules.tt_question_collect.vo.SysAuditUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 审批流程节点表
 * @Author: jeecg-boot
 * @Date: 2021-02-02
 * @Version: V1.0
 */
@Service
public class TtCollectFlowNodeServiceImpl extends ServiceImpl<TtCollectFlowNodeMapper, TtCollectFlowNode>
        implements ITtCollectFlowNodeService {

    @Resource
    private TtCollectFlowNodeMapper auditNodeMapper;

    @Autowired
    private ITtAuditRecordService ttAuditRecordService;

    @Autowired
    private ITtQuestionCollectService ttQuestionCollectService;

    @Autowired
    private PushSysMsgUtil pushSysMsgUtil;

    /**
     * 提交审批流程
     */
    @Override
    @Transactional
    public Result<?> submitProcess(String id, String flowCode,String lclx) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (null == user)
            return Result.error("未查询到当前登录用户信息，请重新登录");
        int isExist = auditNodeMapper.queryCount(id,lclx);
        if (isExist > 0)
             auditNodeMapper.updatescbj(id,lclx);

        List<TtCollectFlowNode> auditList = auditNodeMapper.queryAuditNodeListByFlowCode(flowCode);
        TtQuestionCollect ttQuestionCollect = ttQuestionCollectService.getById(id);

        if (StringUtils.isNotEmpty(auditList)) {
            for (TtCollectFlowNode ttCollectFlowNode : auditList) {
                if (StringUtils.isEmpty(ttCollectFlowNode.getAuditid()))
                    return Result.error("审核预设人员为空");
                List<SysAuditUserVO> auditUserVOs = new ArrayList<SysAuditUserVO>();
                if (AuditNodeType.NODE_ROLES.equals(ttCollectFlowNode.getAudittype())) {
                    // 指定角色
                    auditUserVOs = auditNodeMapper.queryAuditUsersByRoleId(ttCollectFlowNode.getAuditid());
                    if (StringUtils.isEmpty(auditUserVOs))
                        return Result.error("未查询到指定角色下的审核用户");
                }
                else if (AuditNodeType.NODE_USERS.equals(ttCollectFlowNode.getAudittype())) {
                    // 指定人员
                    auditUserVOs = auditNodeMapper
                            .queryAuditUsersByUserIds(getAuditUserIds(ttCollectFlowNode.getAuditid()));
                    if (StringUtils.isEmpty(auditUserVOs))
                        return Result.error("未查询到指定人员对应的审核用户");
                }

                if (AuditNodeType.NODE_CHILD_ALL.equals(ttCollectFlowNode.getAuditchildtype())) {
                    // 全部审核
                    for (SysAuditUserVO sysAuditUserVO : auditUserVOs) {
                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode,
                                sysAuditUserVO.getUserId(), sysAuditUserVO.getUserName(), lclx));
                    }
                }
                else if (AuditNodeType.NODE_CHILD_RANDOM.equals(ttCollectFlowNode.getAuditchildtype())) {
                    // 随机一个审核
                    SysAuditUserVO auditUserVO = getRandomAuditUser(auditUserVOs);
                    ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode,
                            auditUserVO.getUserId(), auditUserVO.getUserName(), lclx));
                }
                else if (AuditNodeType.NODE_CHILD_ARBITRARILY.equals(ttCollectFlowNode.getAuditchildtype())) {
                    // 任意一个审核
                    for (SysAuditUserVO sysAuditUserVO : auditUserVOs) {
                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode, sysAuditUserVO.getUserId(), sysAuditUserVO.getUserName(),lclx));
                    }
                }
                else if (AuditNodeType.NODE_CHILD_PRONAME.equals(ttCollectFlowNode.getAuditchildtype())) {
                    // 产品指定审核

                    //根据产品名称分发到产品负责人审核
                    if ("HZB".equals(ttQuestionCollect.getProname())){

                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode, "40288166787145960178714596e70000", "马坤杰",lclx));

                    }else if("FZCG".equals(ttQuestionCollect.getProname())){
                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode, "40288166781ec123017834b235390020", "王荣豪",lclx));

                    }else if("BHT".equals(ttQuestionCollect.getProname())){
                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode, "40288166781ec1230178346f29c70016", "杨子豪",lclx));

                    }else if("ZHKJ".equals(ttQuestionCollect.getProname())){
                        //其他
                        ttAuditRecordService.save(getAuditEntity(user, ttQuestionCollect, ttCollectFlowNode, "4028816678147fb00178147fbe540002", "李彦学",lclx));

                    }


                }
            }
            //方案审批

            if ("falc".equals(lclx)) {
                //查询角色为方案确认的用户id
                List<Map<String,Object>> fauserids =   auditNodeMapper.queryfauserid();
            	ttQuestionCollect.setFashbj("1");
                for (int i = 0; i <fauserids.size() ; i++) {
                    if( fauserids.get(i).get("USER_ID").equals(user.getId())){
                        ttQuestionCollect.setFashbj("2");
                        ttAuditRecordService.upatefazt(id,lclx);
                    }
                }

			}else {
				//问题审批
				  ttQuestionCollect.setAuditstatus("1");

			}
            ttQuestionCollect.setCreateTime(null);
            ttQuestionCollectService.updateById(ttQuestionCollect);

        }
        else {
        	if ("falc".equals(lclx)) {
        	 	ttQuestionCollect.setFashbj("2");
			}else {
				 ttQuestionCollect.setAuditstatus("2");
			}

            ttQuestionCollectService.updateById(ttQuestionCollect);
        }
        mrSuccess(id);
        try {
        	if("falc".equals(lclx)) {
        		   pushSysMsgUtil.sendMessage(MsgTypeEnum.A07.getMsgTpeCode(), id);
        	}else {
        	  pushSysMsgUtil.sendMessage(MsgTypeEnum.A01.getMsgTpeCode(), id);
			}

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }


        return Result.OK();
    }


    /**
     * 默认审批人是问题提出人时通过
     */
    public void mrSuccess(String id){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //查询sortid排序最大值
        int maxsortid = auditNodeMapper.getmaxsortid(id);
        for (int j = 1; j < maxsortid+1; j++) {
            //查询此级别此问题的审批记录
            List<Map<String,Object>>  res =  auditNodeMapper.queryspusersftcuser(id,String.valueOf(j));
            //查询此级别此问题的是否为待审核状态
            String isnew =  auditNodeMapper.getisnewzt(id,String.valueOf(j));
            System.out.println("排序记录"+j+isnew);
            if ("1".equals(isnew)){
                //待审批
                for (int i = 0; i <res.size() ; i++) {
                    //判断需求提出人是否在此级别审核流程中存在
                    if (user.getId().equals(res.get(i).get("AUDITUSERID"))) {
                        //有---默认通过此人
                        ttAuditRecordService.audit(res.get(i).get("ID").toString(),"1",null,"wtlx",null);

                    }
                }
            }else {
                System.out.println("isnew为2 已审核");
            }
        }
    }


    /**
     * 获取随机人员
     *
     * @param auditUserVOs
     * @return
     */
    private SysAuditUserVO getRandomAuditUser(List<SysAuditUserVO> auditUserVOs) {
        Random random = new Random();
        int n = random.nextInt(auditUserVOs.size());
        return auditUserVOs.get(n);
    }

    /**
     * 获取指定人员信息列表
     *
     * @param auditid
     * @return
     */
    private String getAuditUserIds(String auditid) {
        List<String> auditUserIds = Arrays.asList(auditid.split(","));
        // 线程安全
        StringBuffer sqlUserIds = new StringBuffer("(");
        for (String auditUserId : auditUserIds) {
            sqlUserIds.append("'" + auditUserId + "',");
        }
        return sqlUserIds.substring(0, sqlUserIds.length() - 1) + ")";
    }

    /**
     * 根据实体类和审批流程生成审核数据
     *
     * @param user
     * @param ttQuestionCollect
     * @param ttCollectFlowNode
     * @param userId
     * @param userName
     * @return
     */
    private TtAuditRecord getAuditEntity(LoginUser user, TtQuestionCollect ttQuestionCollect,
                                         TtCollectFlowNode ttCollectFlowNode, String userId, String userName,String lclx) {
        TtAuditRecord ttAuditRecord = new TtAuditRecord();

        ttAuditRecord.setTitle(ttQuestionCollect.getTitlesummary());
        ttAuditRecord.setTablename("tt_question_collect");
        ttAuditRecord.setTableid(ttQuestionCollect.getId());
        ttAuditRecord.setColname("id");
        ttAuditRecord.setColtype("String");
        ttAuditRecord.setNodeid(ttCollectFlowNode.getId());
        ttAuditRecord.setNodename(ttCollectFlowNode.getNodename());
        ttAuditRecord.setNodetype(ttCollectFlowNode.getAudittype());
        ttAuditRecord.setAudittype(ttCollectFlowNode.getAudittype());
        ttAuditRecord.setAuditrange(ttCollectFlowNode.getAuditchildtype());
        ttAuditRecord.setAuditgroupid(ttCollectFlowNode.getAuditid());
        ttAuditRecord.setAuditgroupname(ttCollectFlowNode.getAuditname());

        ttAuditRecord.setAudituserid(userId);
        ttAuditRecord.setAuditusername(userName);
        ttAuditRecord.setLclx(lclx);

        if ("1".equals(ttCollectFlowNode.getSortid())) {
            ttAuditRecord.setIsnew("1");
        }
        else {
            ttAuditRecord.setIsnew("0");
        }
        ttAuditRecord.setSortid(ttCollectFlowNode.getSortid());
        ttAuditRecord.setShbj("0");
        ttAuditRecord.setScbj("0");
        ttAuditRecord.setCreateBy(user.getId());
        ttAuditRecord.setCreateTime(new Date());
        ttAuditRecord.setSysOrgCode(user.getOrgCode());

        return ttAuditRecord;
    }

    @Override
    public List<Map<String, Object>> queryCollectNodesList(String flowcode) {
        // TODO Auto-generated method stub
        return auditNodeMapper.queryCollectNodesList(flowcode);
    }

    @Override
    public int maxSortidByid(String tableid,String lclx) {
        // TODO Auto-generated method stub
        return auditNodeMapper.maxSortidBywtid(tableid,lclx);
    }

    @Override
    public int maxSortidBycode(String flowcode) {
        // TODO Auto-generated method stub
        return null == auditNodeMapper.maxSortidByflowcode(flowcode) ? 0 : auditNodeMapper.maxSortidByflowcode(flowcode);
    }


    @Override
    public List<Map<String, Object>> ids(String auditType, String idname) {
        if ("指定角色".equals(auditType)) {
            return auditNodeMapper.idR(getAuditUserIds(idname));
        }
        return auditNodeMapper.idD(getAuditUserIds(idname));
    }

    // 删除节点
    @Override
    public Result<?> updatesortid(String stortid, String id) {

        TtCollectFlowNode ttCollectFlowNode = getById(id);
        if (null == ttCollectFlowNode) {
            return Result.error("未查询到该数据！");
        }
        int count = auditNodeMapper.Countone(ttCollectFlowNode.getFlowcode(), stortid);
        int isone = auditNodeMapper.isone(ttCollectFlowNode.getFlowcode());
        if (isone == 1) {
            return Result.error("此为最后一个节点，不能删除！");
        }
        // 如果是此级别最后一个节点
        if (count == 1) {
            auditNodeMapper.addSyjsortid(ttCollectFlowNode.getSortid(), ttCollectFlowNode.getFlowcode());
            removeById(id);
        }
        else {
            removeById(id);
        }
        return Result.OK("删除成功！");
    }

    // 更新节点数据

    @Override
    public Result<?> updatebyId(List<Map<String, Object>> listuser, TtCollectFlowNode ttCollectFlowNode) {

        // 删除此流程此级别所有记录
        auditNodeMapper.delmodel(ttCollectFlowNode.getFlowcode(), ttCollectFlowNode.getId());

        // 添加记录
        for (int i = 0; i < listuser.size(); i++) {
            System.out.println(listuser);
            String auditid = (String) listuser.get(i).get("id");
            String username = (String) listuser.get(i).get("realname");
            System.out.println("用户id" + auditid);
            System.out.println("用户名" + username);
            ttCollectFlowNode.setAuditid(auditid);
            ttCollectFlowNode.setAuditname(username);
            ttCollectFlowNode.setId("");
            ttCollectFlowNode.setShbj("0");
            ttCollectFlowNode.setScbj("0");
            save(ttCollectFlowNode);
            //auditNodeMapper.updateInfo(ttCollectFlowNode.getId(), auditid, username);
        }

        return Result.OK();
    }

    @Override
    public Result<?> insertId(List<Map<String, Object>> listuser, TtCollectFlowNode ttCollectFlowNode) {

        if ("tjsyj".equals(ttCollectFlowNode.getBy1())) {
            // 添加上一级,包括当前级别及以下全部级别+1
            auditNodeMapper.addASyjsortid(ttCollectFlowNode.getSortid(), ttCollectFlowNode.getFlowcode());
        }
        else if ("tjxyj".equals(ttCollectFlowNode.getBy1())) {
            // 添加下一级
            auditNodeMapper.delSyjsortid(ttCollectFlowNode.getSortid(), ttCollectFlowNode.getFlowcode());
            ttCollectFlowNode.setSortid(String.valueOf((Integer.valueOf(ttCollectFlowNode.getSortid()) + 1)));
        }
        else {
            // 添加同级
            save(ttCollectFlowNode);
        }

        // 添加此条记录
        for (int i = 0; i < listuser.size(); i++) {
            System.out.println(listuser);
            String auditid = (String) listuser.get(i).get("id");
            String username = (String) listuser.get(i).get("realname");
            System.out.println("用户id" + auditid);
            System.out.println("用户名" + username);
            ttCollectFlowNode.setAuditid(auditid);
            ttCollectFlowNode.setAuditname(username);
            ttCollectFlowNode.setId("");
            ttCollectFlowNode.setShbj("0");
            ttCollectFlowNode.setScbj("0");
            save(ttCollectFlowNode);
        }

        return Result.OK();
    }

	@Override
	public String getfacode() {
		// TODO Auto-generated method stub
		return auditNodeMapper.getfacode();
	}

}
